package gq.example.service;

import gq.example.entity.Users;
import gq.example.mapper.UsersMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class MyUserDetailService implements UserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(MyUserDetailService.class);
    @Autowired
    private UsersMapper usersMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        UserDetails userDetails = null;
        // 根据用户名查询用户
        Users users = usersMapper.findUserByUsername(username);

        if(users == null){
            Users user = usersMapper.findUserByEmail(username);
            if(user == null){
                throw new UsernameNotFoundException("用户不存在");
            }
            userDetails = User.withUsername(user.getUsername())
                    .password(user.getPassword())
                    .build();
        }else {
            userDetails = User.withUsername(users.getUsername())
                    .password(users.getPassword())
                    .build();
        }
        return userDetails;
    }
}
